package com.zhs.gccs.fragment.gccs;

import static com.mapbox.maps.extension.style.expressions.generated.Expression.literal;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.annimon.stream.Stream;
import com.blankj.utilcode.constant.PermissionConstants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.maps.QueriedFeature;
import com.mapbox.maps.Style;
import com.mapbox.maps.extension.style.expressions.generated.Expression;
import com.mapbox.maps.extension.style.layers.properties.generated.IconAnchor;
import com.zhs.gccs.BuildConfig;
import com.zhs.gccs.R;
import com.zhs.gccs.activity.gccs.GccsUserTaskDataDetailActivity;
import com.zhs.gccs.activity.gccs.GccsUserTaskDataFormActivity;
import com.zhs.gccs.dao.TaskGccsDataDao;
import com.zhs.gccs.dao.TaskGccsFileDao;
import com.zhs.gccs.dialog.GccsStatisticsDialog;
import com.zhs.gccs.dialog.LayerExampleDialog;
import com.zhs.gccs.event.EventAddGccs;
import com.zhs.gccs.fragment.BaseFragment;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.CommonCallback;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.http.RequestBodyUpload;
import com.zhs.gccs.listener.FileUploadListener;
import com.zhs.gccs.listener.GccsDataSaveListener;
import com.zhs.gccs.mapbox.ExpressionUtils;
import com.zhs.gccs.mapbox.MapImageUtils;
import com.zhs.gccs.mapbox.MapLegend;
import com.zhs.gccs.mbtiles.LayerConstant;
import com.zhs.gccs.mbtiles.MapLayer;
import com.zhs.gccs.mbtiles.MapLayerLayout;
import com.zhs.gccs.mbtiles.MapLayerPaint;
import com.zhs.gccs.mbtiles.MapSource;
import com.zhs.gccs.model.GccsDict;
import com.zhs.gccs.model.GccsTaskData;
import com.zhs.gccs.model.GccsTaskFile;
import com.zhs.gccs.model.SensorData;
import com.zhs.gccs.model.TaskProject;
import com.zhs.gccs.model.WaterMaker;
import com.zhs.gccs.utils.BitmapUtil;
import com.zhs.gccs.utils.DateUtils;
import com.zhs.gccs.utils.FileUtils;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.PermissionListener;
import com.zhs.gccs.utils.SharedPrefHelper;
import com.zhs.gccs.utils.Utils;
import com.zhs.gccs.view.LocationAddress;
import com.zhs.gccs.view.taskMap.MapBoxView;
import com.zhs.gccs.vo.ApplyGccsTask;
import com.zhs.gccs.vo.BaseBean;
import com.zhs.gccs.vo.GccsDataStatistics;
import com.zhs.gccs.vo.GccsStatistics;
import com.zhs.gccs.vo.GctbListBean;
import com.zhs.gccs.vo.ProjectBoundary;
import com.zhs.gccs.vo.UploadSuccessBean;
import com.zhs.gccs.vo.XmGccsStatisticsBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class GccsMapFragment extends BaseFragment {
    @BindView(R.id.iv_statistics)
    ImageView iv_statistics;
    @BindView(R.id.iv_take_photo)
    ImageView iv_take_photo;
    @BindView(R.id.iv_location)
    ImageView iv_location;
    @BindView(R.id.ll_layer)
    ShapeLinearLayout ll_layer;

    @BindView(R.id.mapboxView)
    MapBoxView mapboxView;
    private SensorData sensorData;//重力加速度及方向
    private LocationAddress locationAddress;//定位信息
    ApplyGccsTask taskBean;
    private TaskGccsDataDao taskGccsDataDao;
    private TaskGccsFileDao taskGccsFileDao;
    //统计数据
    GccsStatistics gccsStatistics;
    private List<String> gccsTypeFilter;//当前选择的工程措施

    @Override
    protected int getLayout() {
        return R.layout.fragment_gccs_map;
    }

    public static GccsMapFragment newInstance(ApplyGccsTask bean) {
        Bundle args = new Bundle();
        args.putSerializable("task", bean);
        GccsMapFragment fragment = new GccsMapFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        taskBean = (ApplyGccsTask) getArguments().getSerializable("task");
        taskGccsDataDao = new TaskGccsDataDao();
        taskGccsFileDao = new TaskGccsFileDao();
        iv_statistics.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if (gccsStatistics == null) {
                    return;
                }
                new GccsStatisticsDialog.Builder(getActivity(),
                        gccsStatistics,
                        gccsTypeFilter, new GccsStatisticsDialog.OnSelectedListener() {
                    @Override
                    public void onSelected(List<String> gccs) {
                        gccsTypeFilter = gccs;
                        //更新地图
                        if(gccs!=null&&gccs.size()>0){
//                            Expression.inExpression(
//                                    Expression.get("my_attribute"), // 需要判断的属性
//                                    Expression.literal(new String[]{"value1", "value2"}) // 给定的数组
//                            );
//                            Expression filter = Expression.eq(Expression.get("gccsType"),
//                                    Expression.literal(gccs));
//                            mapboxView.setLayerFilter(MapLegend.layer_gccs_symbol + "_point",filter);
                            Expression filter = ExpressionUtils.getInArrayExpression("gccsType",gccs);
                            mapboxView.setLayerFilter(MapLegend.layer_gccs_symbol + "_point",filter);
                        }else {
//                            Expression filter = Expression.neq(Expression.get("gccsType"), Expression.literal(""));
//                            mapboxView.setLayerFilter(MapLegend.layer_gccs_symbol + "_point",filter);
                            Expression filter = Expression.eq(Expression.get("gccsType"), Expression.literal(""));
                            mapboxView.setLayerFilter(MapLegend.layer_gccs_symbol + "_point",filter);
                        }
                    }
                }).show();
            }
        });

        iv_location.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                // 定位
                mapboxView.locationToUser();
            }
        });

        ll_layer.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                new LayerExampleDialog.Builder(getActivity()).show();
            }
        });

        iv_take_photo.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                PictureSelector.create(GccsMapFragment.this)
                        .openCamera(SelectMimeType.ofImage())
                        .forResultActivity(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                try {
                                    if(result!=null){
                                        ApplyGccsTask bean = (ApplyGccsTask) getArguments().getSerializable("task");
                                        String path = result.get(0).getRealPath();
                                        writeImageWaterMarker(path);
                                        GccsUserTaskDataFormActivity.start(getActivity(),
                                                bean, path, gccsStatistics,null);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            }
        });
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initView();
        mapboxView.loadOnlineStyle();//立即加载地图
        initPermission(savedInstanceState);
        getXmGccsTypesData();
        //uploadGcccFileSlient();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private void initView() {
        mapboxView.setMapBoxViewListener(new MapBoxView.MapBoxViewListener() {
            @Override
            public void onMapStyleLoaded(Style style) {
                //工程措施
//                style.addImage(MapImageUtils.image_gccs,
//                        MapImageUtils.getImage(context, MapImageUtils.image_gccs));
                //土地平整
                style.addImage("84FC98D87114C32AE050007F0100549D",
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_09));
                //土壤改良
                style.addImage("84FC98D87118C32AE050007F0100549D",
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_08));
                //灌溉和排水
                style.addImage("84FC98D8711EC32AE050007F0100549D",
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_07));
                //田间道路
                style.addImage("84FC98D87133C32AE050007F0100549D",
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_06));
                //农田防护与\n生态环境保护
                style.addImage("84FC98D87138C32AE050007F0100549D",
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_05));
                //农田输配电
                style.addImage("84FC98D8713DC32AE050007F0100549D",
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_04));
                //未设置工程措施的
                style.addImage(defaultIcon,
                        BitmapUtil.getBitmap(context, R.mipmap.gccs_00));


                //初始化地图需要加载的image icon
                style.addImage(MapImageUtils.image_user_location,
                        MapImageUtils.getImage(context, MapImageUtils.image_user_location));
                style.addImage(MapImageUtils.image_gj_start,
                        MapImageUtils.getImage(context, MapImageUtils.image_gj_start));
                style.addImage(MapImageUtils.image_gj_end,
                        MapImageUtils.getImage(context, MapImageUtils.image_gj_end));
                style.addImage(MapImageUtils.image_local_position,
                        MapImageUtils.getImage(context, MapImageUtils.image_local_position));
                style.addImage(MapImageUtils.image_nav_sc,
                        MapImageUtils.getImage(context, MapImageUtils.image_nav_sc));
                loadMapLayers();//加载配置图层
                mapboxView.mapboxInitConfig();//初始化定位等配置
                mapboxView.locationToUser();
                if(!TextUtils.isEmpty(taskBean.getBoundary())){
                    ProjectBoundary boundary = JSON.parseObject(taskBean.getBoundary(),ProjectBoundary.class);
                    Point point = Point.fromLngLat((boundary.getMaxx()+boundary.getMinx())/2,
                            (boundary.getMiny()+boundary.getMaxy())/2);
                    mapboxView.moveCameraTo(point,1000);
                }
                getGccsDataList();//加载项目数据
            }

            @Override
            public void onSensorChanged(SensorData sensor) {
                sensorData = sensor;
            }

            @Override
            public void onLocationChange(LocationAddress location) {
                if (locationAddress == null && location != null) {
                    mapboxView.locationToUser();
                }
                locationAddress = location;
            }

            @Override
            public void onZoomChange(Integer zoom) {

            }

            @Override
            public void onMapClicked(Point point) {
                queryMapFeatureOfClick(point, null);
            }

            @Override
            public void onMapCenterChanged(Point point) {
            }
        });
    }

    private void writeImageWaterMarker(String path) {
        try {
            File file = new File(path);
            FileInputStream fis = new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fis);
            List<WaterMaker> waterMakers = new ArrayList<>();
            DecimalFormat fmt = new DecimalFormat("##0.00000");
            String latlon = "N" + fmt.format(locationAddress.getLon())
                    + "E" + fmt.format(locationAddress.getLat());
            String date = DateUtils.getDateTime();
            waterMakers.add(new WaterMaker("时间：", date));
            waterMakers.add(new WaterMaker("地点：", latlon));//parentActivity.getAddress()));
            waterMakers.add(new WaterMaker("采集人：", SharedPrefHelper.getInstance().getUserAccount()));
            waterMakers.add(new WaterMaker("项目：", taskBean.getPid()));
//            Bitmap textBitmap = BitmapUtil.createWatermark(context, bitmap, waterMakers);
            Bitmap textBitmap = Utils.saveWaterMask(context, 3,
                    bitmap,
                    date,
                    latlon,
                    locationAddress.getAddress(),taskBean.getPid(),
                    SharedPrefHelper.getInstance().getUserAccount());
            FileUtils.saveBitmap(textBitmap, file.getCanonicalPath());
            Utils.writeLatLonIntoJpeg(file.getCanonicalPath(),
                    locationAddress.getLat(),
                    locationAddress.getLon(),
                    date,
                    SharedPrefHelper.getInstance().getUserAccount(),
                    "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadMapLayers() {
        List<MapSource> mapSources = new ArrayList<>();
        //加载系统默认配置图层
        loadLocalMapboundaryLayers(mapSources);
        //加载项目图层
        load2019xmOnlineLayers(mapSources);
        //用户定位图层
        addUserLocationLayer(mapSources);
        loadGccsDataPointLayer(mapSources);//加载工程措施图层
        mapboxView.load(mapSources);
    }




    //加载默认配置图层
    private void loadLocalMapboundaryLayers(List<MapSource> mapSources) {
        try {
            List<MapSource> defaultsSource = JSON.parseArray(
                    FileUtils.readAssetFile(context, "map/zhs_default_map_config.json"),
                    MapSource.class);
            if (defaultsSource != null && defaultsSource.size() > 0) {
                mapSources.addAll(defaultsSource);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void load2019xmOnlineLayers(List<MapSource> mapSources) {
        MapSource source = new MapSource();
        source.setSourceId(MapLegend.source_newxm);
        source.setType(MapSource.type_vector);
        List<String> tiles = new ArrayList<>();
        //http://159.226.205.110:28080/hcApi/gccsLayers/%s/%s/%s/%s/%s/%s
        ///hcApi/gccsLayers/{pid: 项目编码}/{用户账号:useraccount}/{x}/{y}/{z}?token=用户认证token
        String xmlayerUrl = BuildConfig.BASEURL+"gccsLayers/%s/%s/%s/%s/%s?token=%s";
        String url = String.format(xmlayerUrl, taskBean.getPid(),
                SharedPrefHelper.getInstance().getUserAccount(), "{x}", "{y}", "{z}",
                SharedPrefHelper.getInstance().getToken());
        tiles.add(url);
        source.setTiles(tiles);
        List<MapLayer> layers = new ArrayList<>();
        //新建项目 蓝色 07e5ff
        addXmLayerConfig(source.getSourceId(),
                MapLegend.layer_newxm_line, "#07e5ff", 1, 1, null, 5, 20,
                MapLegend.layer_newxm_fill, "#07e5ff", 1, 0.1, null, 5, 20,
                MapLegend.layer_newxm_selected, "#07e5ff", 1, 0.1, Expression.eq(Expression.get("xmbh"), Expression.literal("")), 5, 20,
                MapLegend.layer_newxm_selected_line, "#ffffff", 2, 1, Expression.eq(Expression.get("xmbh"), Expression.literal("")), 5, 20,
                layers);
        ////////////////////////////////////////////////////////////
        addXmLayerConfig(source.getSourceId(),
                MapLegend.layer_gccj_ycj_line, "#ffff00", 1, 1, Expression.eq(Expression.get("xmbh"), Expression.literal("")), 5, 20,
                MapLegend.layer_gccj_ycj_fill, "#ffff00", 1, 0.2, Expression.eq(Expression.get("xmbh"), Expression.literal("")), 5, 20,
                MapLegend.layer_gccj_ycj_selected, "#ffff00", 1, 0.2, Expression.eq(Expression.get("xmbh"), Expression.literal("")), 5, 20,
                MapLegend.layer_gccj_ycj_selected_line, "#ffffff", 2, 1, Expression.eq(Expression.get("xmbh"), Expression.literal("")), 5, 20,
                layers);
        source.setLayers(layers);
        mapSources.add(source);
    }

    private void addXmLayerConfig(String sourceId,
                                  String layer1Id, String layer1Color, double layer1Width,
                                  double layer1Opacity, Expression layer1Filter, int layer1Min, int layer1Max,
                                  String layer2Id, String layer2Color, double layer2Width, double layer2Opacity, Expression
                                          layer2Filter, int layer2Min, int layer2Max,
                                  String layer3Id, String layer3Color, double layer3Width, double layer3Opacity, Expression
                                          layer3Filter, int layer3Min, int layer3Max,
                                  String layer4Id, String layer4Color, double layer4Width, double layer4Opacity, Expression
                                          layer4Filter, int layer4Min, int layer4Max,
                                  List<MapLayer> layersxm) {
        MapLayer linelayer = new MapLayer();
        linelayer.setLayerId(layer1Id);
        linelayer.setType(MapLayer.Type_line);
        linelayer.setSourceId(sourceId);
        linelayer.setMaxzoom(layer1Max);
        linelayer.setMinzoom(layer1Min);
        linelayer.setFilter(layer1Filter);
        linelayer.setSourceLayer(taskBean.getPid());
        MapLayerPaint xmfhlPaint = new MapLayerPaint();
        xmfhlPaint.setType(MapLayerPaint.Type_line);
        xmfhlPaint.setColor(layer1Color);
        xmfhlPaint.setWidth(layer1Width);
        xmfhlPaint.setOpacity(layer1Opacity);
        linelayer.setPaint(xmfhlPaint);
        layersxm.add(linelayer);

        MapLayer fillFlayer = new MapLayer();
        fillFlayer.setLayerId(layer2Id);
        fillFlayer.setType(MapLayer.Type_fill);
        fillFlayer.setSourceId(sourceId);
        fillFlayer.setMaxzoom(layer2Max);
        fillFlayer.setMinzoom(layer2Min);
        fillFlayer.setFilter(layer2Filter);
        fillFlayer.setSourceLayer(taskBean.getPid());
        MapLayerPaint fillPaint = new MapLayerPaint();
        fillPaint.setType(MapLayerPaint.Type_fill);
        fillPaint.setColor(layer2Color);
        fillPaint.setOutlineColor(layer2Color);
        fillPaint.setWidth(layer2Width);
        fillPaint.setOpacity(layer2Opacity);
        fillFlayer.setPaint(fillPaint);
        layersxm.add(fillFlayer);

        MapLayer fillSelectedFlayer = new MapLayer();
        fillSelectedFlayer.setLayerId(layer3Id);
        fillSelectedFlayer.setType(MapLayer.Type_fill);
        fillSelectedFlayer.setSourceId(sourceId);
        fillSelectedFlayer.setMaxzoom(layer3Max);
        fillSelectedFlayer.setMinzoom(layer3Min);
        fillSelectedFlayer.setFilter(layer3Filter);
        fillSelectedFlayer.setSourceLayer(taskBean.getPid());
        MapLayerPaint fillSelectedPaint = new MapLayerPaint();
        fillSelectedPaint.setType(MapLayerPaint.Type_fill);
        fillSelectedPaint.setColor(layer3Color);
        fillSelectedPaint.setOutlineColor(layer3Color);
        fillSelectedPaint.setWidth(layer3Width);
        fillSelectedPaint.setOpacity(layer3Opacity);
        fillSelectedFlayer.setPaint(fillSelectedPaint);
        layersxm.add(fillSelectedFlayer);

        MapLayer lineSelectlayer = new MapLayer();
        lineSelectlayer.setLayerId(layer4Id);
        lineSelectlayer.setType(MapLayer.Type_line);
        lineSelectlayer.setSourceId(sourceId);
        lineSelectlayer.setMaxzoom(layer4Max);
        lineSelectlayer.setMinzoom(layer4Min);
        lineSelectlayer.setFilter(layer4Filter);
        lineSelectlayer.setSourceLayer(taskBean.getPid());
//        lineSelectlayer.setSourceLayer("gbnt_4490_110000");
        MapLayerPaint xmselectPaint = new MapLayerPaint();
        xmselectPaint.setType(MapLayerPaint.Type_line);
        xmselectPaint.setColor(layer4Color);
        xmselectPaint.setWidth(layer4Width);
        xmselectPaint.setOpacity(layer4Opacity);
        lineSelectlayer.setPaint(xmselectPaint);
        layersxm.add(lineSelectlayer);
    }

    private void addUserLocationLayer(List<MapSource> mapSources) {
        MapSource gccjDataSource = new MapSource();
        String sourceId = LayerConstant.sourceOfUserLocation;
        gccjDataSource.setSourceId(sourceId);
        gccjDataSource.setType(MapSource.type_geojson);
        List<MapLayer> layers = new ArrayList<>();
        //注意聚合之后的点位必须用 circle 类型的图层来表示
        //聚合图层
        //https://blog.csdn.net/lz5211314121/article/details/132038592
        //脉冲
        //
        MapLayer simplelayer = new MapLayer();
        simplelayer.setLayerId(LayerConstant.layerOfUserLocation);
        simplelayer.setType(MapLayer.Type_symbol);
        simplelayer.setSourceId(sourceId);
        MapLayerLayout layout = new MapLayerLayout();
        layout.setImage(literal(MapImageUtils.image_user_location));//(Expression.get("icon"));
        String sizeEx = "[\"interpolate\",[\"linear\"],[\"zoom\"] , 8, 1.2,10, 1.4,13,1.6]";
        layout.setSize(Expression.fromRaw(sizeEx));
//        String rotateEx = "[\"get\", \"angle\"]";
//        layout.setRotate(Expression.fromRaw(rotateEx));
        simplelayer.setLayout(layout);
        layers.add(simplelayer);

        gccjDataSource.setLayers(layers);
        mapSources.add(gccjDataSource);
    }

    //加载工程抽检图层
    //目前一个任务的抽检数据不会特别大，我们用接口实现，后期可能改成geoserver图层
    private void loadGccsDataPointLayer(List<MapSource> mapSources) {
        List<GccsTaskData> datas = new ArrayList<>();//taskGccsDataDao.findListByTaskId(taskBean.getId());
        List<Feature> features = loadGccsFeatureData(datas);
        FeatureCollection featureCollection = FeatureCollection.fromFeatures(features);
        MapSource dataSource = new MapSource();
        String sourceId = MapLegend.source_gccs;
        dataSource.setSourceId(sourceId);
        dataSource.setType(MapSource.type_geojson);
        dataSource.setGsonData(featureCollection);
        dataSource.setCluster(false);
//        dataSource.setClusterRadius(50l);//聚合半径clusterRadius，这个半径越大会检索到越广的范围进行聚合
//        dataSource.setClusterMaxZoom(10);//指定聚合最大层级clusterMaxZoom，这表示当超过这个最大层级之后。就不会有聚合效果了
        List<MapLayer> layers = new ArrayList<>();
        //非聚类图层
        MapLayer layer = new MapLayer();
        layer.setLayerId(MapLegend.layer_gccs_symbol + "_point");
        layer.setType(MapLayer.Type_symbol);
        layer.setSourceId(sourceId);
        layer.setMinzoom(4);
        layer.setMaxzoom(24);
        MapLayerLayout layerLayout = new MapLayerLayout();
        layerLayout.setImage(Expression.get("icon"));
//        layerLayout.setImage(literal(MapImageUtils.image_user_location));
//        layerLayout.setSize(Expression.literal(0.75));
        String sizeEx = "[\"interpolate\",[\"linear\"],[\"zoom\"] ,4, 0.3, 22,1]";
        layerLayout.setSize(Expression.fromRaw(sizeEx));
//                String sizeEx = "[\"interpolate\",[\"linear\"],[\"zoom\"] , 12, 1.2,16, 1.4,20,1.6,20,1.8]";
//        String sizeEx = "[\"interpolate\",[\"linear\"],[\"zoom\"] ,4, 0.3, 22,1.4]";
//        layerLayout.setSize(Expression.fromRaw(sizeEx));
//                layerLayout.setOffset(new Expression([0,14]));
//                layerLayout.setOffset(Expression.fromRaw("[-20,-53]"));
        String rotateEx = "[\"get\", \"angle\"]";
        layerLayout.setRotate(Expression.fromRaw(rotateEx));
        layerLayout.setAnchor(IconAnchor.TOP_LEFT);
        layer.setLayout(layerLayout);
        layers.add(layer);
        //注意聚合之后的点位必须用 circle 类型的图层来表示
        //聚类图层
//        MapLayer layerClusterCircle = new MapLayer();
//        layerClusterCircle.setLayerId(MapLegend.layer_gccs_symbol + "_cluster_circle");
//        layerClusterCircle.setType(MapLayer.Type_circle);
//        layerClusterCircle.setSourceId(sourceId);
//        //layer.setMinzoom(16);
//        MapLayerLayout layerLayoutClusterCircle = new MapLayerLayout();
//        String colorEx = "[\"step\", [\"get\", \"point_count\"],\"#51bbd6\",20, \"#f1f075\", 50, \"#f28cb1\"]";
//        layerLayoutClusterCircle.setColor(Expression.fromRaw(colorEx));
//        String sizeEx = "[\"step\", [\"get\", \"point_count\"], 20, 20, 30, 50, 40]";
//        layerLayoutClusterCircle.setSize(Expression.fromRaw(sizeEx));
//        layerClusterCircle.setLayout(layerLayoutClusterCircle);
//        String filter = "[\"has\", \"point_count\"]";
//        layerClusterCircle.setFilter(Expression.fromRaw(filter));
//        layers.add(layerClusterCircle);

//        MapLayer circleTextLayer = new MapLayer();
//        circleTextLayer.setLayerId(MapLegend.layer_gccs_symbol + "_cluster_count");
//        circleTextLayer.setType(MapLayer.Type_symbol);
//        circleTextLayer.setSourceId(sourceId);
//        MapLayerLayout layoutCircleText = new MapLayerLayout();
//        layoutCircleText.setTextField(Expression.fromRaw("[\"get\", \"iconType\"]"));
//        layoutCircleText.setTextFont(Expression.fromRaw("[\"DIN Offc Pro Medium\", \"Arial Unicode MS Bold\"]"));
//        layoutCircleText.setTextSize(Expression.literal(16));
//        circleTextLayer.setLayout(layoutCircleText);
//        MapLayerPaint circleTextTextPaint = new MapLayerPaint();
//        circleTextTextPaint.setColor("white");
//        circleTextLayer.setPaint(circleTextTextPaint);
//        layers.add(circleTextLayer);
        dataSource.setLayers(layers);
        mapSources.add(dataSource);
    }


    private void getGccsDataList() {
//        Map<String, Object> hashMap = new HashMap<>();
//        hashMap.put("taskType", "2");//taskType;//任务类型  1：核查任务  2：工程抽查任务
//        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault()
                        .xmGccsList(taskBean.getPid(), "", "", 10000, 0),
                new ProgressObserver(this.getActivity(), false) {
                    @Override
                    protected void _onNext(String result) {
//                        GccsTaskDataPageListBean bean = JSON.parseObject(result, GccsTaskDataPageListBean.class);
                        GctbListBean bean = new Gson().fromJson(result, GctbListBean.class);
                        if (bean != null && bean.getCode() == 200 && bean.getRows() != null && bean.getRows().size() > 0) {
                            List<GccsTaskData> rows = bean.getRows();
                            Stream.of(rows).forEach(item -> {
                                taskGccsDataDao.addOrUpdate(item);
                                if (item.getFileList() != null) {
                                }
                            });

                        }
                        updateGccsLayerData();
                    }

                    @Override
                    protected void _onError(String result) {
                    }
                });
    }

    private void updateGccsLayerData() {//更新工程抽检图层数据
        List<GccsTaskData> datas = taskGccsDataDao.findByPid(taskBean.getPid());
        List<Feature> features = loadGccsFeatureData(datas);
        FeatureCollection gccjDataGson = FeatureCollection.fromFeatures(features);
        String sourceId = MapLegend.source_gccs;
        mapboxView.updateGsonSourceData(sourceId, gccjDataGson);
    }

    private List<Feature> loadGccsFeatureData(List<GccsTaskData> datas) {
        //mapbox.html showMedia
//        List<CaDictStatisData> mData = caLayerDataDao.
//                findByStatisDictId(caType.getDictId(),smTask.getTaskid());
        //如果data是空 的构造一个空的Feature作为图层数据源
        List<Feature> features = new ArrayList<>();
        if (datas != null) {
            for (GccsTaskData item : datas) {
                try {
                    Point point = Point.fromLngLat(Double.parseDouble(item.getLongitude()),
                            Double.parseDouble(item.getLatitude()));
                    Feature mFeatures = Feature.fromGeometry(point);
                    mFeatures.addStringProperty("gccs", "gccs");
                    mFeatures.addStringProperty("id", item.getId());
                    mFeatures.addStringProperty("userId", item.getUserExec());
                    String icon = item.getGccsPType();
                    if(TextUtils.isEmpty(item.getGccsType())){
                        icon = defaultIcon;
                    }
                    mFeatures.addStringProperty("icon", icon);//MapImageUtils.image_gccs);//em.getGccsType());//MapImageUtils.getImageId(caType.getDictCode()));
                    //mFeatures.addStringProperty("angle", item.get);
//                    String iconType = getIconType(item.getGccsPType());
//                    mFeatures.addStringProperty("iconType", iconType);
                    mFeatures.addStringProperty("pid", item.getPid());
                    mFeatures.addStringProperty("taskId", item.getTaskId());
                    mFeatures.addStringProperty("gccsType", TextUtils.isEmpty(item.getGccsType())?
                            defaultIcon:item.getGccsType());
                    mFeatures.addStringProperty("address", item.getAddress());
                    mFeatures.addStringProperty("remarks", item.getRemarks());
                    features.add(mFeatures);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return features;
    }
    private String defaultIcon = "1111111111111111111111111111111";
    private String getIconType(String gccsPType) {
        if ("84FC98D87114C32AE050007F0100549D".equals(gccsPType)) {
            return "1";
        } else if ("84FC98D87118C32AE050007F0100549D".equals(gccsPType)) {
            return "2";
        } else if ("84FC98D8711EC32AE050007F0100549D".equals(gccsPType)) {
            return "3";
        } else if ("84FC98D87133C32AE050007F0100549D".equals(gccsPType)) {
            return "4";
        } else if ("84FC98D87138C32AE050007F0100549D".equals(gccsPType)) {
            return "5";
        } else if ("84FC98D8713DC32AE050007F0100549D".equals(gccsPType)) {
            return "6";
        }
        return "0";//未选择工程措施的
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventAddGccs event) {
        //重新加载数据
        getXmGccsTypesData();
        updateGccsLayerData();//初始页面已经获取了列表，提交数据也保存了，所以这个只需要从本地查询更新地图就可以了
    }

    @Override
    public void onAttach(Context mContext) {
        super.onAttach(mContext);
        if (mapboxView != null) {
            mapboxView.onDestroy();
        }
    }

    private void initPermission(Bundle savedInstanceState) {
        requestPermission(getActivity(), new PermissionListener() {
                    @Override
                    public void onSucceed() {
                        initData();
                    }

                    @Override
                    public void onFailed() {
                        initPermission(savedInstanceState);
                    }
                }, PermissionConstants.STORAGE, PermissionConstants.CAMERA,
                PermissionConstants.MICROPHONE,
                PermissionConstants.LOCATION);
    }

    private void initData() {

    }

    //地图点击查询
    private void queryMapFeatureOfClick(Point point, TaskProject taskProject) {
        mapboxView.queryMapPointFeatures(point, new MapBoxView.MapBoxQueryListener() {
            @Override
            public void onQuery(List<QueriedFeature> featureList) {
                if (featureList == null || featureList.size() == 0) {
                    return;
                }
                for (QueriedFeature query : featureList) {
                    Feature feature = query.getFeature();
                    if (feature == null) continue;
                    if (feature.hasProperty("gccs")) {
                        //点击的是核查反馈
                        showCurrentGccc(feature.getStringProperty("id"), point);
                        break;//不让再循环其他feature了
                    }
                }
            }
        });
    }

    private void showCurrentGccc(String dataId, Point point) {
        GccsUserTaskDataDetailActivity.start(getActivity(),dataId,taskBean,gccsStatistics);
    }

    private void getXmGccsTypesData() {
        toSubscribeSingleOb(Api.getDefault().
                        getXmGccsStatistics(taskBean.getPid()),
                new ProgressObserver(this.getActivity(), false) {
                    @Override
                    protected void _onNext(String result) {
                        XmGccsStatisticsBean bean = new Gson().fromJson(result, XmGccsStatisticsBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (bean != null && bean.getCode() == 200) {
                            gccsStatistics = bean.getData();
                            if (gccsStatistics.getXmGccs() != null) {
                                Stream.of(gccsStatistics.getXmGccs()).forEach(xmgccs -> {
                                    if (gccsStatistics.getGccs() != null) {
                                        GccsDict gccs = Stream.of(gccsStatistics.getGccs()).
                                                filter(i -> xmgccs.getDbid().equals(i.getDbid())).findFirstOrElse(null);
                                        if (gccs != null) {
                                            xmgccs.setTypeName(gccs.getMc2());
                                            xmgccs.setInt("1".equals(gccs.getIsInt()));
                                        }
                                    }
                                    if (gccsStatistics.getXmGccsReport() != null) {
                                        GccsDataStatistics report = Stream.of(gccsStatistics.getXmGccsReport()).
                                                filter(i -> xmgccs.getDbid().equals(i.getDbid())).findFirstOrElse(null);
                                        if (report != null) {
                                            xmgccs.setReportCount(report.getRwl());
                                        }
                                    }
                                    gccsTypeFilter = new ArrayList<>();
                                    Stream.of(gccsStatistics.getXmGccs()).forEach(i->{
                                        gccsTypeFilter.add(i.getDbid());
                                    });
                                });
                            }
                        } else {

                        }
                    }

                    @Override
                    protected void _onError(String result) {
                        Log.e("_onError", result);
                    }
                });
    }
    ////////////////////////////////////////////////
//    private void uploadGcccFileSlient() {
//        //v_file_upload_tips.
//        List<GccsTaskFile> caFiles = taskGccsFileDao.
//                findNeedSyncListByTaskId(taskBean.getId());
//        if (caFiles == null || caFiles.size() == 0) {
//            return;
//        }
//        GccsTaskFile file = caFiles.get(0);
//        if (TextUtils.isEmpty(file.getLocalUrl())) {
//            return;
//        }
//        HashMap<String, String> params = new HashMap<>();
//        params.put("pid", file.getPid());
//        List<String> loaclFilePaths = new ArrayList<>();
//        if ("0".equals(file.getFileType())) {
//            loaclFilePaths.add(file.getLocalUrl());
//        } else if ("2".equals(file.getFileType())) {//视频
//            loaclFilePaths.add(file.getLocalUrl());
//            //缩略图
//            if (file.getVideoThumbLocalUrl() != null) {
//                loaclFilePaths.add(file.getVideoThumbLocalUrl());
//            }
//        }
//        toUploadGcccFiles(loaclFilePaths, params, new FileUploadListener() {
//            @Override
//            public void onSuccess(String data) {
//                Type type = TypeToken.getParameterized(BaseBean.class, GccsTaskFile.class).getType();
//                BaseBean<GccsTaskFile> bean = new Gson().fromJson(data, type);
//                if (bean != null && bean.getCode() == 200) {
//                    GccsTaskFile finalCjFile = bean.getData();
//                    file.setFilePath(finalCjFile.getFilePath());
//                    file.setBucket(finalCjFile.getBucket());
//                    file.setObjectName(finalCjFile.getObjectName());
//                    file.setFileName(finalCjFile.getFileName());
//                    file.setUniqueName(finalCjFile.getUniqueName());
//                    file.setFileSize(finalCjFile.getFileSize());
//                    file.setFileExt(finalCjFile.getFileExt());
//
//                    saveGccsDataFile(file, new GccsDataSaveListener() {
//                        @Override
//                        public void onSuccess(String result) {
//                            Type type = TypeToken.getParameterized(BaseBean.class, UploadSuccessBean.class).getType();
//                            BaseBean<UploadSuccessBean> bean = new Gson().fromJson(result, type);
//                            if (bean != null && bean.getData() != null) {
////                                file.setSync(true);
////                                file.setId(bean.getData().getid() + "");//服务器文件id
////                                taskGccsFileDao.addOrUpdate(file);
//                                taskGccsFileDao.deleteByLocalId(file.getLocalId());
//                                uploadGcccFileSlient();
//                            }
//                        }
//
//                        @Override
//                        public void onError() {
//                            uploadGcccFileSlient();
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void onError() {
//
//            }
//        });
//    }
//
//    private void toUploadGcccFiles(List<String> loaclFilePaths,
//                                   HashMap<String, String> params,
//                                   FileUploadListener listener) {
//        String contentType = "multipart/form-data";
//        List<MultipartBody.Part> parts = new ArrayList<>();
//        for (String filePath : loaclFilePaths) {
//            File file = new File(filePath);
//            RequestBody requestFile = RequestBody.create(MediaType.parse(contentType), file);
//            RequestBodyUpload requestBodyUpload = new RequestBodyUpload(requestFile, file.getName(), new CommonCallback.OnProgressWithNameCallBack() {
//                @Override
//                public void onProgress(String filename, float percent) {
//                    Log.e("xp", "filename = " + filename + ", percent = " + percent);
//                }
//            });
//            MultipartBody.Part filePartBody = MultipartBody.Part.
//                    createFormData("file", file.getName(), requestBodyUpload);
//            parts.add(filePartBody);
//        }
//        //构造参数
//        Map<String, RequestBody> _params = new HashMap<>();
//        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<String, String> entry = iterator.next();
//            RequestBody requestBody = RequestBody.
//                    create(MediaType.parse(contentType),
//                            entry.getValue());
//            _params.put(entry.getKey(), requestBody);
//        }
//        toSubscribeSingleOb(Api.getDefault()
//                        .gccsUploadFile(_params, parts),
//                new ProgressObserver(this.getActivity(), false) {
//                    @Override
//                    protected void _onNext(String result) {
//                        Log.e("CZF", "gccsUploadFile：" + result);
//                        listener.onSuccess(result);
//                    }
//
//                    @Override
//                    protected void _onError(String result) {
//                        Log.e("CZF", "gccsUploadFile：" + result);
//                        listener.onError();
//                    }
//                });
//    }
//    private void saveGccsDataFile(GccsTaskFile file, GccsDataSaveListener listener) {
//        Map hashMap = JSON.parseObject(JSON.toJSONString(file));
//        RequestBody requestBody = createRequestBody(hashMap);
//        toSubscribeSingleOb(Api.getDefault()
//                        .saveGccsFile(requestBody),
//                new ProgressObserver(this.getActivity(), false) {
//                    @Override
//                    protected void _onNext(String result) {
//                        if (listener != null) listener.onSuccess(result);
//                    }
//
//                    @Override
//                    protected void _onError(String result) {
//                        if (listener != null) listener.onError();
//                    }
//                });
//    }
}
